package com.zjj.jvm2.memAllocation;

import lombok.Data;
import org.openjdk.jol.info.ClassLayout;

/**
 * @author zhanglei.zjj
 * @description 测试栈上分配
 * 结论：
 * 使用如下参数不会发生GC
 * -Xmx15m -Xms15m -XX:+DoEscapeAnalysis -XX:+PrintGC -XX:+EliminateAllocations
 * 使用如下参数都会发生大量GC
 * -Xmx15m -Xms15m -XX:-DoEscapeAnalysis -XX:+PrintGC -XX:+EliminateAllocations
 * -Xmx15m -Xms15m -XX:+DoEscapeAnalysis -XX:+PrintGC -XX:-EliminateAllocations
 *
 * @date 2023/3/8 23:56
 */
public class TestAllocationOnStack {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();

        // 这里大概总共会用1G的内存
        for (int i = 0; i < 1024 * 1024 * 500; i++) {
            alloc();
        }
        long end = System.currentTimeMillis();
        System.out.println("cost：" + (end - start));
    }

    /**
     * 每次分配大概1MB空间
     */
    private static void alloc() {
        HelpA helpA = new HelpA();
        helpA.setAge(26);
        helpA.setName("zjj");
    }
}

@Data
class HelpA {
    private int age;
    private String name;

    // 测试一个helpA实例 占24byte
    public static void main(String[] args) {
        HelpA helpA = new HelpA();
        helpA.setAge(26);
        helpA.setName("zjj");

        ClassLayout helpALayout = ClassLayout.parseInstance(helpA);
        System.out.println("helpALayout size: " + helpALayout.toPrintable());
    }
}
